// Copyright (C) 1953-2022 NUDT
// Verilog module name - sync_period_timing 
// Version: V4.1.0.20221207
// Created:
//         by - fenglin 
////////////////////////////////////////////////////////////////////////////
// Description:
//         
///////////////////////////////////////////////////////////////////////////

`timescale 1ns / 1ps

module sync_period_timing
#(
parameter clk_period = {8'd8,41'h0}//8ns
) 
(
        i_clk  ,
        i_rst_n,
		
        i_gm_role	       ,
        iv_sync_period     ,		

        o_sync_generate_pulse
);
// clk & rst
input                  i_clk;
input                  i_rst_n;

input                  i_gm_role;
input      [3:0]       iv_sync_period  ;

output reg             o_sync_generate_pulse;   
//////////////////ns count/////////////////
reg        [25:0]       rv_ns_cnt;    
always @(posedge i_clk or negedge i_rst_n) begin
    if(!i_rst_n)begin
	    rv_ns_cnt          <= 26'b0;
    end
    else begin
	    if(i_gm_role)begin
			if(rv_ns_cnt + clk_period[48:25] >= {10'd1000,16'b0})begin
				rv_ns_cnt <= rv_ns_cnt + clk_period[48:25] - {10'd1000,16'b0};
			end
			else begin
				rv_ns_cnt <= rv_ns_cnt + clk_period[48:25];
			end
	    end
		else begin
		    rv_ns_cnt          <= 26'b0;
		end
    end
end
//////////////////us count/////////////////
reg        [9:0]       rv_us_cnt;    
always @(posedge i_clk or negedge i_rst_n) begin//us count
    if(!i_rst_n)begin
	    rv_us_cnt          <= 10'b0;
    end
    else begin
        if(i_gm_role)begin		
		   if(rv_us_cnt >= 10'd999)begin
		  //    if(rv_us_cnt >= 10'd19)begin
				rv_us_cnt <= 10'd0;
			end
			else begin
				if(rv_ns_cnt + clk_period[48:25] >= {10'd1000,16'b0})begin
				    rv_us_cnt <= rv_us_cnt + 1'd1;
			    end
				else begin
				    rv_us_cnt <= rv_us_cnt;
				end
			end
		end
		else begin
		    rv_us_cnt          <= 10'b0;
		end
    end
end 
//////////////////ms count/////////////////
reg        [15:0]       rv_ms_cnt;    
always @(posedge i_clk or negedge i_rst_n) begin//ms count
    if(!i_rst_n)begin
	    rv_ms_cnt          <= 16'b0;
		o_sync_generate_pulse      <= 1'b0 ;
    end
    else begin
		if(i_gm_role)begin		
			if(rv_ms_cnt >= (16'd1 << iv_sync_period))begin
				rv_ms_cnt          <= 16'd0;
				o_sync_generate_pulse      <= 1'b1;
			end
			else begin
				if(rv_us_cnt >= 10'd999)begin
				//  if(rv_us_cnt >= 10'd19)begin
				    rv_ms_cnt <= rv_ms_cnt + 1'd1;
			    end
				else begin
				    rv_ms_cnt <= rv_ms_cnt;
				end				
				o_sync_generate_pulse      <= 1'b0;
			end
		end
		else begin
			rv_ms_cnt          <= 16'b0;
			o_sync_generate_pulse      <= 1'b0 ;
		end	
    end
end    

endmodule